package com.simonall.utils;

import com.simonall.enums.ResponseCodeEnum;

import cn.hutool.http.ContentType;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

/**
 * Netty Response Build
 * 
 * @author simonall
 */
public final class NettyResponseUtil {

	public static void build(ChannelHandlerContext ctx, ResponseCodeEnum response) {
		build(ctx, Response.build(response));
	}

	public static void build(ChannelHandlerContext ctx, Response<?> response) {
		build(ctx, response.toJson());
	}

	public static void build(ChannelHandlerContext ctx, String body) {
		ByteBuf content = Unpooled.copiedBuffer(body, CharsetUtil.UTF_8);
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
		response.headers().set(HttpHeaderNames.CONTENT_TYPE, ContentType.JSON.getValue());
		response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
		ctx.writeAndFlush(response);
	}

}
